package net.oxygen.upload.exception;

import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import net.oxygen.upload.enums.BizCodeEnum;
import net.oxygen.upload.util.JsonData;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.List;

/**
 * <p>
 * 功能：全局异常处理器
 * </p>
 *
 * @author 陈伟伟
 * @since 2023/12/13 10:46
 */
@ControllerAdvice
@Slf4j
public class CustomExceptionHandler {

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public JsonData handleBiz(BizException e) {
        log.error("[业务异常]{}",e.getMessage(), e);
        return JsonData.codeAndMsg(e.getCode(), e.getMessage());
    }

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public JsonData handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        if (!errors.isEmpty()) {
            String errorMessage = errors.get(0).getDefaultMessage();
            log.error("[接口参数错误]{}", errorMessage);
            return JsonData.codeAndMsg(BizCodeEnum.BAD_REQUEST.getCode(), errorMessage);
        } else {
            log.error("[接口参数错误]{}", e.getMessage());
            return JsonData.result(BizCodeEnum.BAD_REQUEST);
        }
    }

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    @ResponseBody
    public JsonData handleValidationException(ValidationException e) {
        log.error("[接口参数错误]{}", e.getMessage());
        return JsonData.result(BizCodeEnum.BAD_REQUEST);
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JsonData handleBindException(BindException e) {
        log.error("[接口参数错误]{}", e.getMessage());
        return JsonData.result(BizCodeEnum.BAD_REQUEST, e.getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public JsonData handleConstraintViolationException(ConstraintViolationException e) {
        log.error("[接口参数错误]{}", e.getMessage());
        return JsonData.result(BizCodeEnum.BAD_REQUEST);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public JsonData handlerNoFoundException(Exception e) {
        log.error("访问路径不存在", e);
        return JsonData.codeAndMsg(404, "路径不存在，请检查路径是否正确");
    }

    /**
     * 请求缺少必要参数异常处理
     */
    @ExceptionHandler(value = { HttpMessageNotReadableException.class, MissingServletRequestParameterException.class})
    @ResponseBody
    public JsonData handleMissingArgument() {
        return JsonData.result(BizCodeEnum.BAD_REQUEST);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonData handle(Exception e) {
        log.error("[系统异常]{}", e.getMessage(), e);
        return JsonData.error("全局异常，未知错误");
    }
}
